package sword.T55;

import util.TreeNode;

/**
 * @Author: 18362
 * @Create: 2022-04-10 0:51:02 星期日
 */
public class Solution2 {

    private boolean flag = true;

    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        int leftDepth = getDepth(root.left), rightDepth = getDepth(root.right);
        if (!flag)
            return false;
        return Math.abs(leftDepth-rightDepth) < 2;
    }

    public int getDepth(TreeNode root) {
        if (root == null)
            return 0;
        int leftDepth = getDepth(root.left), rightDepth = getDepth(root.right);
        if (Math.abs(leftDepth-rightDepth) > 1)
            flag = false;
        return Math.max(leftDepth, rightDepth) + 1;
    }
}
